# !/usr/bin/evn python3
# -*- coding: utf-8 -*-
# File Name: payment.py
# Created Date: 2017-12-06 10:36:45
from app.extra import *
import random
import pingpp

pingpp.api_key = "sk_live_v5Sm5OOinjDGKS0e1CyPifLO"
class Payment(db.Model):
    __tablename__ = 'payments'
    id = db.Column(db.Integer, primary_key=True)
    charge_id = db.Column(db.String, index=True)
    serial_number = db.Column(db.String, index=True, nullable=False, unique=True)
    order_id = db.Column(db.Integer, index=True, nullable=False)
    user_id = db.Column(db.Integer, index=True, nullable=False)
    price  = db.Column(db.Integer, default=0)
    body = db.Column(db.String)
    subject = db.Column(db.String)
    pay_channel = db.Column(db.String, default="alipay")
    pay_status = db.Column(db.Integer, default=1)
    currency = db.Column(db.String, default="cny")
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)


    def __init__(self, **kwargs):
        super(Payment, self).__init__(**kwargs)
        self.serial_number = random.getrandbits(32)

    def __repr__(self):
        return "<Payment no:{}, user:{}, order:{}>".format(self.serial_number, self.user_id, self.order_id)

    def charge(self, ip="127.0.0.1"):
        ch = pingpp.Charge.create(
                order_no=self.serial_number,
                channel="alipay",
                amount=self.price,
                subject=self.subject,
                body = self.body,
                currency=self.currency,
                app = dict(id="app_aDS4q1OmjDWDzTWv"),
                client_ip=ip
                )
        self.charge_id  = ch["id"]
        db.session.commit()
        return ch
    
